<?php

namespace App\Http\Controllers\Api\CMS;

use App\Http\Resources\ContentMediaResource;
use App\Models\CMS\Content;
use App\Models\CMS\Media;
use App\Models\CMS\Picture;
use App\Services\CmsService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ContentMediaController extends Controller
{
    /**
     * 构造方法
     * @var CmsService
     */
    public $cmsService;

    public function __construct()
    {
        $this->cmsService = new CmsService();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $category_id = $request->get('category_id', []);
        $models = Media::query()->when($category_id, function ($query) use ($category_id) {
            return $query->whereHas('contents.categorylabel', function ($q) use ($category_id) {
                foreach ($category_id as $item) {
                    $q->where('category_path', 'like', "%{$item}%");
                }
            });
        })->when($keyword, function ($query) use ($keyword) {
            $query->whereHas('contents.category', function ($q) use ($keyword) {
                $q->where('name', 'like', '%' . $keyword . '%');
            })->orWhereHas('contents', function ($q) use ($keyword) {
                $q->where('title', 'like', '%' . $keyword . '%');
            });
        })->with('contents.category', 'contents.categorylabel', 'contents')
            ->orderByDesc('cms_content_media.id')->paginate();
        return ContentMediaResource::collection($models);
    }

    /**
     * @param Request $request
     * @return ContentMediaResource
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $columns = $this->syncColumns($data['category']);
        DB::beginTransaction();
        try {
            $content = new Content();
            $content->fill($data);
            $content->content_detail_type = 'ContentMedia';
            $content->content_detail_id = 0;
            $content->status = 1;
            $tags = $data['tags'];
            $this->cmsService->asyncTags($tags);
            $content->tags = json_encode($tags);
            $content->view_count = $content->view_count ? $content->view_count : 0;
            $content->save();
            $ContentMedia = new Media();
            $ContentMedia->fill($data);
            $ContentMedia->content_id = $content->id;
            $ContentMedia->save();
            $content->content_detail_id = $ContentMedia->id;
            $content->save();
            $content->category()->sync($columns);
            DB::commit();
            return new ContentMediaResource($ContentMedia);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($e->getMessage(), 422);
        }
    }

    /**
     * 格式化栏目参数
     * @param $column
     * @return array
     */
    protected function syncColumns($column)
    {
        $arr = [];
        foreach ($column as $item) {
            if ($item) {
                $arr[end($item)] = ['category_path' => '-' . implode("-", $item) . '-'];
            }
        }
        return $arr;
    }

    /**
     * @param $cpId
     * @return ContentMediaResource
     */
    public function show($cpId)
    {
        $model = $this->findModel($cpId);
        return new ContentMediaResource($model);
    }

    /**
     * @param Request $request
     * @param $cpId
     * @return ContentMediaResource
     */
    public function update(Request $request, $cpId)
    {
        $data = $request->all();
        $columns = $this->syncColumns($data['category']);
        DB::beginTransaction();
        try {
            $ContentMedia = $this->findModel($cpId);
            $ContentMedia->fill($data);
            $content = $ContentMedia->contents;
            $content->fill($data);
            $tags = $data['tags'];
            $this->cmsService->asyncTags($tags);
            $content->tags = json_encode($tags);
            $content->save();
            $ContentMedia->save();
            $content->category()->sync($columns);
            DB::commit();
            return new ContentMediaResource($ContentMedia);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($e->getMessage(), 422);
        }
    }

    /**
     * @param $cpId
     * @return array
     * @throws \Exception
     */
    public function destroy($cpId)
    {
        $model = Media::query()->where('id', $cpId)->first();
        $content = $model->contents;
        $content->delete();
        $model->delete();
        return response()->json(['删除成功']);
    }

    protected function findModel($cpId)
    {
        $model = Media::query()->with('contents.category', 'contents.categorylabel','asset')->where('id', $cpId)->first();
        return $model;
    }

    protected function getCategoryIdStr($categoryIdArr)
    {

        return implode(',', $categoryIdArr);
    }

}
